<!DOCTYPE html>
<html lang="en-us">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title> Memcache </title>

  <link rel="stylesheet" media="screen" href="/css/style.css" >
</head>
<body>

  <header class="site-header">
    <h3 class="site-title">
      <a href="https://mkaz.github.io/working-with-go/">
        Working with Go
      </a>
    </h3>
  </header>

  <main>

    <aside>
      <h2>Contents</h2>
      <ul>
        
          <li><a href="/hello.html">Hola Mundo</a></li>
        
          <li><a href="/strings.html">Strings</a></li>
        
          <li><a href="/slices.html">Slices</a></li>
        
          <li><a href="/functions.html">Functions</a></li>
        
          <li><a href="/control-structures.html">Control Structures</a></li>
        
          <li><a href="/for-loops.html">For Loops</a></li>
        
          <li><a href="/structs.html">Structs</a></li>
        
          <li><a href="/maps.html">Maps</a></li>
        
          <li><a href="/files.html">Files</a></li>
        
          <li><a href="/read-dir.html">Directories</a></li>
        
          <li><a href="/objects.html">Objects</a></li>
        
          <li><a href="/command-line.html">Command-line</a></li>
        
          <li><a href="/date-time.html">Date/Time</a></li>
        
          <li><a href="/sorting.html">Sorting</a></li>
        
          <li><a href="/json.html">JSON</a></li>
        
          <li><a href="/web-server.html">Web Server</a></li>
        
          <li><a href="/guess-game.html">Guessing Game</a></li>
        
          <li><a href="/rest-api.html">REST API</a></li>
        
          <li><a href="/regexps.html">Regexp</a></li>
        
          <li><a href="/memcache.html">Memcache</a></li>
        
          <li><a href="/mysql.html">MySQL</a></li>
        
          <li><a href="/interfaces.html">Interfaces</a></li>
        
          <li><a href="/testing.html">Testing</a></li>
        
      </ul>
    </aside>

    <article class="entry-content">
      <h1>Storing Objects in Memcache</h1>

<p>How to store objects in memcache using <a href="https://github.com/bradfitz/gomemcache">bradfitz/gomemcache</a> package. Memcache stores data as <code>[]byte</code>, so you need to first encode the object prior to storing.</p>

<p>I typically encode using JSON, often the data is already or will soon be in JSON format, plus human readable helps debugging. If space and performance is a concern, see <a href="https://golang.org/pkg/encoding/gob/"><code>encoding/gob</code></a> for another format.</p>

<pre><code class="language-go">package main

import (
	&quot;encoding/json&quot;
	&quot;fmt&quot;

	&quot;github.com/bradfitz/gomemcache/memcache&quot;
)

// define Dog object type
type Dog struct {
	Name  string
	Color string
}

func main() {

	// connect to memcache server
	mc := memcache.New(&quot;127.0.0.1:11211&quot;)

	// try to pull from memcache
	fetchItem, err := mc.Get(&quot;dog&quot;)

	// check for cache hit
	if err != memcache.ErrCacheMiss {
		if err != nil {
			fmt.Println(&quot;Error fetching from memcache&quot;, err)
		} else {
			fmt.Println(&quot;Cache hit!&quot;)

			dog, err := DecodeData(fetchItem.Value)
			if err != nil {
				fmt.Println(&quot;Error decoding data from memcache&quot;, err)
			} else {
				fmt.Println(&quot;Dog name is: &quot;, dog.Name)
			}
		}
	}

	// create instance of object and set properties
	spot := Dog{Name: &quot;Spot&quot;, Color: &quot;brown&quot;}

	// create memcache item to store
	setItem := memcache.Item{Key: &quot;dog&quot;, Value: EncodeData(spot), Expiration: 300}

	err = mc.Set(&amp;setItem)
	if err != nil {
		fmt.Println(&quot;Error setting memcache item&quot;, err)
	}

	// run twice
}

func DecodeData(raw []byte) (dog Dog, err error) {
	err = json.Unmarshal(raw, &amp;dog)
	return dog, err
}

func EncodeData(dog Dog) []byte {
	enc, err := json.Marshal(dog)
	if err != nil {
		fmt.Println(&quot;Error encoding Action to JSON&quot;, err)
	}
	return enc
}
</code></pre>

    </article>

  </main>

<footer class="site-footer" role="contentinfo">
    An <a href="https://mkaz.blog/">mkaz</a> joint
    <span class="sep"> | </span>
    <a href="https://github.com/mkaz/hasite">Powered by Hastie</a>
</footer>

<script src="/js/asciinema/asciinema-player.js"></script>
<script src="/js/prism.js"></script>

</body>
</html>